package cn.haut.online_read.webmagic;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * @author xing
 * @date 2021-04-04 18:42
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class GithubRepoPageProcessor implements PageProcessor {

    // 部分一：抓取网站的相关配置，包括编码、抓取间隔、重试次数等
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);
//    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Override
    // process是定制爬虫逻辑的核心接口，在这里编写抽取逻辑
    public void process(Page page) {
        page.putField("title", page.getHtml().xpath("//title/text()").toString());
        page.putField("list", page.getHtml().xpath("//div[@class='sort']/div[@class='sort-cells']//a/text()").all().toString());
//        page.putField("links", page.getHtml().links().regex("http://zhuishushenqi.com/book/.*").all().toString());
        page.putField("links", page.getHtml().links().regex("^http://zhuishushenqi.com/book/\\w*$").all().toString());
        page.addTargetRequests(page.getHtml().links().regex("^http://zhuishushenqi.com/book/\\w*$").all());
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new GithubRepoPageProcessor())
                .addUrl("http://zhuishushenqi.com/category?gender=male")
                .addPipeline(new FilePipeline("C:/Users/17385/Desktop/Context/"))
                .addPipeline(new ConsolePipeline())
                //开启5个线程抓取
                .thread(5)
                //启动爬虫
                .run();
    }
}
